/**
 * @Description: 页面路由容器组件
 * @Author: gengzhaoji
 */
import { Navigate, useLocation, useNavigate } from 'react-router-dom';

let temp = null;

export default function Guard({ element, meta = {}, onRouteBefore }) {
	const { pathname } = useLocation();

	const navigate = useNavigate();

	if (onRouteBefore) {
		if (temp === element) return element;

		const pathRes = onRouteBefore({ pathname, meta });
		if (Object.prototype.toString.call(onRouteBefore).match(/\s(\w+)\]/)[1] === 'Promise') {
			pathRes.then((res) => {
				if (res && res !== pathname) navigate(res, { replace: true });
			});
		} else {
			if (pathRes && pathRes !== pathname) element = <Navigate to={pathRes} replace={true} />;
		}
	}

	temp = element;
	return element;
}
